﻿using Camera.MAUI.ZXingHelper;
using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;
using Compass.Maui.Pages.FinishGoods;
using Compass.Maui.Services.FinishGoods;

namespace Compass.Maui.ViewModels.FinishGoods;

[QueryProperty(nameof(PackingListDto), nameof(PackingListDto))]
public partial class WarehousingPageViewModel : BaseViewModel
{
    private readonly IPalletService _palletService;
    private readonly IPackingListService _packingListService;
    private readonly INavigationService _navigationService;

    public WarehousingPageViewModel(IPalletService palletService, IPopupService popupService,IPackingListService packingListService,INavigationService navigationService)
    {
        _palletService = palletService;
        _packingListService = packingListService;
        _navigationService = navigationService;
        palletService.Update += PalletServiceOnUpdate;
    }

    [ObservableProperty]
    private PackingListDto? packingListDto;

    public ObservableRangeCollection<PalletDto> PalletDtos { get; } = new();

    [ObservableProperty]
    private string result;

    [ObservableProperty]
    private bool duplicate;

    [RelayCommand]
    private async Task GetPalletDtosAsync()
    {
        await IsBusyFor(async () =>
        {
            try
            {
                if (PackingListDto is null)
                {
                    PalletDtos.Clear();
                    return;
                }

                PalletDtos.ReplaceRange(await _palletService.GetPalletsByPackingListIdAsync(PackingListDto.Id!.Value));
            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error!", $"Unable to get pallets:{e.Message}", "OK");
            }
        });
    }

    [RelayCommand]
    private void BarcodesDetected(BarcodeEventArgs e)
    {
        //注意，不管是什么操作都需要放在主线程中执行
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await IsBusyFor(async () =>
            {
                Result = e.Result.First().Text;
                //导航到托盘详细页面
                //todo:检查二维码的是否是托盘码，检查是不是当前项目的托盘,使用toast进行提示
                if (!Result.Contains("pallet"))
                {
                    await Toast.Make("此二维码不是托盘的。").Show();
                    return;
                }

                //如果是直接扫码的，就查询PackingListDto
                if (PackingListDto is null)
                {
                    var odpNumber = Result.Split('_')[1];
                    var dto =await _packingListService.GetPackingListDtoByOdpNumberAsync(odpNumber);
                    if (dto is null)
                    {
                        await Toast.Make("无法查询到装箱信息。").Show();
                        return;
                    }
                    PackingListDto = dto;
                    await GetPalletDtosAsync();
                }
                else
                {
                    if (!Result.Contains(PackingListDto.OdpNumber))
                    {
                        await Toast.Make("此托盘不是当前项目的。").Show();
                        return;
                    }
                }
                await _navigationService.NavigateToAsync(nameof(WarehousingPalletPage),
                    new Dictionary<string, object?>
                    {
                        {nameof(Result),Result},
                        {nameof(PackingListDto),PackingListDto}
                    });
                //使用模式导航?
                //await Shell.Current.Navigation.PushModalAsync(
                //    new WarehousingPalletPage(new WarehousingPalletPageViewModel { Result = Result }));
            });
        });
    }

    //响应Pallet更新事件，更新入库时间
    private void PalletServiceOnUpdate(object? sender, PalletUpdateEventArgs e)
    { 
        PalletDtos.Replace(e.UpdatedPalletDto);
    }
}